<template>
  <div class="w_h_100">

    <div class="box search" ref="searchRef">
      <div class="inlet">待办任务 > 融资单笔待办 > <span class="size">保后</span></div>
      <myform :fields="fields1" @handleSelect="handleSelect" :model="values" class="m_t_10" :options="options"
        v-if="!isExpand">
      </myform>
      <myform :fields="fields" :model="values" @handleSelect="handleSelect" class="m_t_10" :options="options"
        v-if="!isExpand">
        <template v-slot:guaMoney>
          <div class="d_f a_i_c">
            <el-input v-model="values.guaMoneyStart" placeholder="请输入" type="number" />
            <span class="padding">至</span>
            <el-input v-model="values.guaMoneyEnd" placeholder="请输入" type="number" />
          </div>
        </template>
      </myform>
      <div class="d_f j_c_s_b" v-if="!isExpand">
        <span></span>
        <div class="btn d_f a_i_c">
          <el-button @click="resetting">重置</el-button>
          <el-button type="primary" :icon="Search" @click="searchFor">搜索</el-button>
          <span class="expand d_f a_i_c" @click="screen(true)">收起筛选 <img src="../../../assets/up.png" alt=""
              class="m_l_5"></span>
        </div>
      </div>
      <div v-if="isExpand" class="d_f j_c_s_b m_t_10">
        <myform :fields="fields1" @handleSelect="handleSelect" :model="values" class="" :options="options">
        </myform>
        <div class="btn d_f a_i_c">
          <el-button @click="resetting">重置</el-button>
          <el-button type="primary" :icon="Search" @click="searchFor">搜索</el-button>
          <span class="expand d_f a_i_c" @click="screen(false)">展开筛选 <img src="../../../assets/below.png" alt=""
              class="m_l_5"></span>
        </div>
      </div>
    </div>
    <div class="mytable m_t_10 " :style="{ height: `calc(100% - ${height})` }">
      <div class="d_f j_c_s_b a_i_c">
        <h4>融资单笔待办列表</h4>
        <div>
          <el-button v-if="type != 'isPreRelease'" :disabled="selection.length == 0 ? true : false"
            v-hasPerm="'refundSingleFinancingBehind'" @click="submit('isApplyRefund')">申请退费</el-button>
          <el-button v-if="type != 'isApplyRefund'" :disabled="selection.length == 0 ? true : false"
            v-hasPerm="'insuranceSingleFinancingBehind'" type="primary" @click="submit('isPreRelease')">提前解保</el-button>

        </div>
      </div>
      <mytable :fields="tableFields" @selecSelection="selecSelection" :type="type" :isSelection="isSelection"
        width="110" ref="tableRef" :values="values" api="runTaskListByPage" class="m_t_10">
        <template v-slot:timeLimit="{ row }">
          <span>{{ row.timeLimit || '0' }}天</span>
        </template>
        <template v-slot:approveStatus="{ row }">
          <div class="normal_status" v-if="row.approveStatus != 6">
            <img src="../../../assets/normal.png" alt="" class="normal_img">
            <span>正常</span>
          </div>
          <div class="abnormal" v-else>
            <img src="../../../assets/abnormal.png" alt="" class="normal_img">
            <span>超时</span>
          </div>
        </template>
        <template v-slot:customerStatus="{ row }">
          <div class="success_status" v-if="row.masterStatus == 0">
            <img src="../../../assets/normal.png" alt="" class="status_img">
            <span>正常</span>
          </div>
          <div class="success_status" v-if="row.masterStatus == 1">
            <img src="../../../assets/normal.png" alt="" class="status_img">
            <span>在途</span>
          </div>
          <div class="pause_status" v-if="row.masterStatus == 2">
            <img src="../../../assets/pause.png" alt="" class="status_img">
            <span>暂停</span>
          </div>
          <div class="settle_status" v-if="row.masterStatus == 3">
            <img src="../../../assets/settle.png" alt="" class="status_img">
            <span>结清</span>
          </div>
          <div class="settle_status" v-if="row.masterStatus == 4">
            <img src="../../../assets/settle.png" alt="" class="status_img">
            <span>解保</span>
          </div>
          <div class="abnormal_status" v-if="row.masterStatus == 5">
            <img src="../../../assets/abnormal.png" alt="" class="status_img">
            <span>逾期</span>
          </div>
          <div class="extension_status" v-if="row.masterStatus == 6">
            <img src="../../../assets/extension.png" alt="" class="status_img">
            <span>展期</span>
          </div>
          <div class="noRead_status1" v-if="row.masterStatus == 7">
            <img src="../../../assets/noRead.png" alt="" class="status_img">
            <span>预警</span>
          </div>
          <div class="compensation_status" v-if="row.masterStatus == 8">
            <img src="../../../assets/compensation.png" alt="" class="status_img">
            <span>代偿</span>
          </div>
        </template>
        <template v-slot:projectNo="{ row }">
          <div class="d_f a_i_c">
            <div class="isRead" v-if="row.isRead == 0"></div>
            <div class="noRead" v-else></div>
            {{ row.projectNo }}
          </div>
        </template>
        <template v-slot:operation="{ row }">
          <div class="d_f j_c_s_b">
            <el-button type="primary" size="small" :icon="EditPen" plain @click="handle(row)">处理</el-button>
          </div>
        </template>
      </mytable>
    </div>
    <component class="m_t_20" :is="FormComponents['ryfp']" v-if="taskId" :isEnabled="1" ref="ryfp" type="useForm"
    @resultData="resultData" />
  </div>
</template>

<script lang='ts'>
import { defineComponent, reactive, toRefs, onBeforeMount, ref, getCurrentInstance } from 'vue'
import { Search, EditPen } from '@element-plus/icons-vue'
import { copy } from '../../../utils/date'
import { useRouter } from 'vue-router'
import { deptList } from '../../../api/system/authority'
import { productListAll } from '../../../api/system/institution'
import { cooperativeAgencyListAll } from '../../../api/system/flowPath'
import { runTaskApplyRefund, runTaskPreRelease,runTaskAssign } from '../../../api/agent'
import { Message } from '../../../utils/resetMessage'
import { ElMessageBox } from 'element-plus'
import { singleFinancingBehindType } from '../../../type/agent'
import { FormComponents } from '../../../components/formChildren/myComponents'
const values = {
  productId: "",//产品名称
  findKey: '',//项目搜索
  agencyProjectId: '',//合作机构
  deptId: '',//业务部门
  guaStartTime: '',//担保开始时间
  guaEndTime: '',//担保结束时间
  start: [],
  end: [],
  nodeName: '',
  province: '',
  city: '',
  county: '',
  nodeCategory: 2,
  guaMoneyStart: '',
  guaMoneyEnd: '',
  finishShstartTime: '',
  finishEndTime: '',
  category: 1,
  nodeId: '',

}
export default defineComponent({
  name: '',
  setup() {
    const data: singleFinancingBehindType = reactive({
      fields1: [
        {
          label: "产品名称",
          prop: 'productId',
          placeholder: '请选择',
          type: 'select',
          bindLabel: 'name',
          bindValue: 'id',
          labelWidth: '70px'
        },
        {
          label: "项目搜索",
          prop: 'findKey',
          placeholder: '请输入客户名称/项目编号',
          type: 'input',
          labelWidth: '70px'
        },
      ],
      fields: [
        {
          label: "经办机构",
          prop: 'agencyProjectId',
          placeholder: '请选择',
          type: 'select',
          labelWidth: '70px',
          bindLabel: 'name',
          bindValue: 'id',
        },
        {
          label: "业务部门",
          prop: 'deptId',
          placeholder: '请选择',
          type: 'select',
          labelWidth: '70px',
          bindLabel: 'name',
          bindValue: 'id',
        },
        {
          label: "担保起始日期",
          prop: 'start',
          placeholder: '请选择',
          type: 'range',
          labelWidth: '110px',
        },
        {
          label: "到期日期",
          prop: 'end',
          placeholder: '请选择',
          type: 'range',
          labelWidth: '70px',
        },
        {
          label: "担保金额",
          prop: 'guaMoney',
          labelWidth: '70px',
        },
        {
          label: "所在省",
          prop: 'province',
          placeholder: '请选择',
          type: 'select',
          labelWidth: '70px',
          bindLabel: 'name',
          bindValue: 'name',
        },
        {
          label: "所在盟市",
          prop: 'city',
          placeholder: '请选择',
          type: 'select',
          labelWidth: '70px',
          bindLabel: 'name',
          bindValue: 'name',
        },
        {
          label: "所在旗县",
          prop: 'county',
          placeholder: '请选择',
          type: 'select',
          labelWidth: '70px',
          bindLabel: 'name',
          bindValue: 'name',
        },
        {
          label: "当前任务",
          prop: 'nodeId',
          placeholder: '请选择',
          type: 'select',
          labelWidth: '70px',
          bindLabel: 'nodeName',
          bindValue: 'nodeId',
        },

      ],
      options: {
        deptId: [],
        productId: [],
        agencyProjectId: [],
        province: [],
        city: [],
        county: [],
        nodeId: [],
      },
      values: copy(values),
      isExpand: true,
      tableFields: [
        {
          label: '项目编号',
          prop: 'projectNo',
          width: '300px',
        },
        {
          label: '产品名称',
          prop: 'productName',
          width: '250px',
        },
        {
          label: '客户名称',
          prop: 'customerName',
          width: '150px',
        },
        {
          label: '经办机构',
          prop: 'cooperativeAgencyName',
          width: '250px',
        },
        {
          label: '地区',
          prop: 'area',
          width: '200px',
        },
        {
          label: '业务部门',
          prop: 'deptName',
          width: '150px',
        },
        {
          label: '担保总额（元）',
          prop: 'totalMoney',
          width: '150px',
        },
        {
          label: '进件时间',
          prop: 'applyTime',
          width: '200px',
        },
        {
          label: '规定完成时间',
          prop: 'timeLimit',
          width: '150px',
        },
        {
          label: '当前任务',
          prop: 'nodeName',
          width: '250px',
        },
        {
          label: '更新时间',
          prop: 'updateTime',
          width: '180px',
        },
        {
          label: '审批状态',
          prop: 'approveStatus',
          width: '150px',
        },
        // {
        //   label: '业务状态',
        //   prop: 'customerStatus',
        //   width: '150px',
        // },
      ],

      areaProps: {
        multiple: false,
        value: 'name',
        label: 'name',
        children: 'districts',
        checkStrictly: true
      },
      districts: [],
      height: '160px',
      isSelection: true,
      type: '',
      selection: [],
      taskId: '',
      ids: [],
    })
    const router = useRouter()
    const tableRef = ref()
    const searchRef = ref()
    const ryfp = ref()
    onBeforeMount(() => {
      data.options.province = JSON.parse(localStorage.getItem('districts'))
      methods.getList()
      // statusTrigger({})
    })
    const currentInstance = getCurrentInstance()//获取全局挂载实例
    const methods = {

      selecSelection(selection: any) {
        data.selection = selection.map((item: any) => {
          return item.id
        })
      },
      //申请解保跟提前解保提交
      submit(type: string) {

        if (type == 'isApplyRefund') {
          ElMessageBox.confirm(
            '是否申请退费？',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
          )
            .then(() => {
              runTaskApplyRefund({ ids: data.selection }).then((res: any) => {
                Message({ type: 'success', message: '提交成功' })
                if (res.length > 0) {
                  data.ids = res
                  data.taskId = res[0]
                }
                methods.searchFor()
                tableRef.value.clearSelection()
                data.type = ''
              }).catch(() => {
                data.type = ''
              })
            }).catch(() => {
              data.type = ''
            })
        } else {
          ElMessageBox.confirm(
            '是否提前解保？',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
          )
            .then(() => {
              runTaskPreRelease({ ids: data.selection }).then((res: any) => {
                Message({ type: 'success', message: '提交成功' })
                if (res.length > 0) {
                  data.ids = res
                  data.taskId = res[0]
                }
                methods.searchFor()
                data.type = ''
              }).catch(() => {
                data.type = ''
              })
            }).catch(() => {
              data.type = ''
            })
        }
      },
      //获取查询条件数据
      getList() {
        deptList({}).then((res: any) => {
          data.options.deptId = res
        })
        productListAll({ category: 1 }).then((res: any) => {
          data.options.productId = res
        })
        cooperativeAgencyListAll({}).then((res: any) => {
          data.options.agencyProjectId = res
        })
      },
      //是否展开筛选
      screen(flag: boolean) {
        data.isExpand = flag
        data.values = copy(values)
        setTimeout(() => {
          data.height = searchRef.value.offsetHeight + 60 + 'px'
        }, 100)
      },
      //进入详情处理业务
      handle(row: any) {
        router.push({ path: '/agent/singleFinancing/nodeProcessing', query: { id: row.id, projectId: row.projectId, type: 2, flowInstId: row.flowInstId, category: data.values.category, nodeId: row.nodeId } })
      },
      //表格数据重置
      resetting() {
        data.values = copy(values)
        tableRef.value.resettingTable(data.values)
        data.options.city=data.options.county=data.options.nodeId=[]
      },
      //搜索
      searchFor() {
        if (data.values.start) {
          if (data.values.start.length > 0) {
            data.values.guaStartTime = data.values.start[0]
            data.values.guaEndTime = data.values.start[1]
          } else {
            data.values.guaStartTime = data.values.guaEndTime = ''
          }
        } else {
          data.values.guaStartTime = data.values.guaEndTime = ''
        }
        if (data.values.end) {
          if (data.values.end.length > 0) {
            data.values.finishShstartTime = data.values.end[0]
            data.values.finishEndTime = data.values.end[1]
          } else {
            data.values.finishShstartTime = data.values.finishEndTime = ''
          }
        } else {
          data.values.finishShstartTime = data.values.finishEndTime = ''
        }
        tableRef.value.handleCurrentChange(1)
      },
      //根据选择省市区获取相关数据
      handleSelect(props: string) {
        if (props == 'province') {
          data.values.city = ''
          data.values.county = ''
          data.options.city = data.options.county = []
          data.options.province.map(item => {
            if (item.name == data.values.province) {
              data.options.city = item.districts
            }
          })
        } if (props == 'city') {
          data.values.county = ''
          data.options.city.map(item => {
            if (item.name == data.values.city) {
              data.options.county = item.districts
            }
          })
        } if (props == 'productId') {
          if(!data.values.productId){
            data.options.nodeId=[]
            data.values.nodeId=''
            return
          }
          let flowId = ''
          data.options.productId.map((item: any) => {
            if (item.id == data.values.productId) {
              flowId = item.flowId
            }
          })
          let fun = currentInstance?.appContext.config.globalProperties.$tablejs.runTaskListByPage
          fun({ flowId: flowId, pageNum: 1,productId:data.values.productId, pageSize: 1000000000, nodeGroupFlag: 1, nodeCategory: data.values.nodeCategory, category: data.values.category }).then((res: any) => {
            res.records.map((item:any)=>{
              item.nodeName=item.nodeName+'('+item.nodeCount+')'
            })
            data.options.nodeId = res.records
            data.values.nodeId = ''
          })
        }
      },
      resultData(val) {
        runTaskAssign({ taskId: data.taskId, empId: val.empId }).then(() => {
          Message({ type: 'success', message: '提交成功' })
          ryfp.value.clearValue()
          data.ids = data.ids.filter((item: any) => {
            return item != data.taskId
          })
          if (data.ids.length > 0) {
            data.taskId = data.ids[0]
          }else{
            data.taskId=''
          }
        })
      }
    }
    return {
      ...toRefs(data),
      Search, EditPen,
      ...methods, tableRef, searchRef,FormComponents,ryfp
    }
  }
})
</script>
<style scoped lang='scss'>
.box {
  width: calc(100% - 64px);
  background: #fff;
  box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, 0.1);
  border-radius: 6px;
  padding: 10px 32px;
  margin-top: 10px;
}

.mytable {
  overflow-y: auto;
  width: calc(100% - 64px);
  background: #fff;
  box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, 0.1);
  border-radius: 6px;
  padding: 24px 32px;
  height: calc(100% - 200px);
}

.padding {
  padding: 0px 5px;
}

.expand {
  color: #1878FF;
  font-size: 14px;
  margin-left: 8px;
  cursor: pointer;
}

.isRead {
  background: #D54941;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 10px;
}

.noRead {
  width: 8px;
  height: 8px;
  margin-right: 10px;
}
</style>
<style lang='scss'>
.search {
  .el-form-item {
    margin-bottom: 10px !important;
  }

  .el-input,
  .el-select {
    width: 200px !important;
  }
}
</style>